<?php
declare (strict_types = 1);

namespace app\common\middleware\http;

use think\Request;
use think\Response;

class AllowOriginMiddleware
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle(Request $request, \Closure $next) : Response
    {
        if (strtoupper($request->method()) == "OPTIONS") {
            return Response::create('', 'html', 200)
                ->header([
                    'Access-Control-Allow-Origin' => '*',
                    'Access-Control-Allow-Headers' => 'Authorization, Sec-Fetch-Mode, DNT, X-Mx-ReqToken, Keep-Alive, User-Agent, If-Match, If-None-Match, If-Unmodified-Since, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Accept-Language, Origin, Accept-Encoding,Access-Token,token,version',
                    'Access-Control-Allow-Methods' => 'GET, POST, PATCH, PUT, DELETE, OPTIONS',
                    'Access-Control-Max-Age' => '1728000',
                    'Access-Control-Allow-Credentials' => 'true'
                ]);
        }

        $response = $next($request);
        
        if ($response instanceof Response) {
            $response->header([
                'Access-Control-Allow-Origin' => '*',
                'Access-Control-Allow-Headers' => 'Authorization, Sec-Fetch-Mode, DNT, X-Mx-ReqToken, Keep-Alive, User-Agent, If-Match, If-None-Match, If-Unmodified-Since, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Accept-Language, Origin, Accept-Encoding,Access-Token,token,version',
                'Access-Control-Allow-Methods' => 'GET, POST, PATCH, PUT, DELETE, OPTIONS',
                'Access-Control-Max-Age' => '1728000',
                'Access-Control-Allow-Credentials' => 'true'
            ]);
        }

        return $response;
    }
}
